"""
摄像头传感器模块
提供摄像头数据采集和处理功能
"""

import cv2
import numpy as np
from typing import Dict, Any, Optional
import asyncio
import time


class CameraSensor:
    """摄像头传感器类"""

    def __init__(self, config: Dict[str, Any]):
        """
        初始化摄像头传感器

        Args:
            config: 配置字典，包含摄像头参数
        """
        self.config = config
        self.camera_url = config.get(
            "camera_url", "http://localhost:8080/?action=stream"
        )
        self.cap = None
        self._init_camera()
        self._start_capture_task()

    def _init_camera(self) -> None:
        """初始化摄像头"""
        try:
            self.cap = cv2.VideoCapture(self.camera_url)
            if not self.cap.isOpened():
                print(f"无法打开摄像头流: {self.camera_url}")
                self.cap = None
            else:
                print(f"成功连接到摄像头流: {self.camera_url}")
        except Exception as e:
            print(f"摄像头初始化失败: {e}")
            self.cap = None

    def _start_capture_task(self) -> None:
        """启动摄像头数据采集任务"""
        loop = asyncio.get_event_loop()
        loop.create_task(self._update_camera())

    async def _update_camera(self) -> None:
        """更新摄像头数据"""
        while True:
            try:
                if self.cap and self.cap.isOpened():
                    ret, frame = self.cap.read()
                    if ret:
                        # 可以在这里添加图像处理逻辑
                        pass
                await asyncio.sleep(0.033)  # 约30fps
            except Exception as e:
                print(f"摄像头数据更新失败: {e}")
                await asyncio.sleep(1)

    async def get_frame(self) -> Optional[np.ndarray]:
        """
        获取当前帧

        Returns:
            当前帧图像，如果获取失败则返回None
        """
        if self.cap and self.cap.isOpened():
            ret, frame = self.cap.read()
            if ret:
                return frame
        return None

    async def get_frame_base64(self) -> Optional[str]:
        """
        获取当前帧的base64编码

        Returns:
            当前帧的base64编码字符串，如果获取失败则返回None
        """
        frame = await self.get_frame()
        if frame is not None:
            _, buffer = cv2.imencode(".jpg", frame)
            return buffer.tobytes().hex()
        return None

    async def get_sensor_data(self) -> Dict[str, Any]:
        """
        获取传感器数据

        Returns:
            包含图像数据和时间戳的字典
        """
        frame_base64 = await self.get_frame_base64()
        if frame_base64:
            return {"image": frame_base64, "timestamp": time.time()}
        return {"error": "Camera not available", "timestamp": time.time()}

    async def close(self) -> None:
        """关闭摄像头"""
        if self.cap:
            self.cap.release()
